package com.ldq.imooc.basics.io;

/**
 * @Author : 李道泉
 * @Description : Java进制转换
 * @Date : 2018/4/2 15:01
 * @Modified by :
 */
public class BinaryConversion {

    public static void main(String[] args) {

        //转为二进制
        System.out.println(Integer.toBinaryString(123));
        //转为八进制
        System.out.println(Integer.toOctalString(123));
        //转为十六进制
        System.out.println(Integer.toHexString(123));

        byte[] arr = BinaryConversion.int2Bytes(2308);
        System.out.println(arr[0] + " " + arr[1] + " " + arr[2] + " " + arr[3]);

        System.out.println(BinaryConversion.bytes2Int(arr));


        byte[] arrlong = BinaryConversion.long2bytes(19940730);
        System.out.println(arrlong[0] + " " + arrlong[1] + " " + arrlong[2] + " " + arrlong[3] + " " + arrlong[4] + " " + arrlong[5] + " " + arrlong[6] + " " + arrlong[7]);

        System.out.println(BinaryConversion.bytes2Int(arrlong));

    }

    /**
     * @Author : 李道泉
     * @Description : int转byte
     * @Date 2018/4/2 15:46
     * @Modified by :
     */
    public static byte[] int2Bytes(int num) {

        byte[] arr = new byte[4];
        arr[0] = (byte) ((num >> 0 * 8) & 0xff);
        arr[1] = (byte) ((num >> 1 * 8) & 0xff);
        arr[2] = (byte) ((num >> 2 * 8) & 0xff);
        arr[3] = (byte) ((num >> 3 * 8) & 0xff);

        return arr;
    }

    /**
     * @Author : 李道泉
     * @Description : byte转int
     * @Date 2018/4/2 15:59
     * @Modified by :
     */
    public static int bytes2Int(byte[] arr) {

        int rs0 = (arr[0] & 0xff) << 0 * 8;
        int rs1 = (arr[1] & 0xff) << 1 * 8;
        int rs2 = (arr[2] & 0xff) << 2 * 8;
        int rs3 = (arr[3] & 0xff) << 3 * 8;

        int result = 0;
        for (int i = 0; i < arr.length; i++) {
            result += (arr[i] & 0xff) << i * 8;
        }

        return result;
    }

    /**
     * @Author : 李道泉
     * @Description : byte转long
     * @Date 2018/4/2 16:14
     * @Modified by :
     */
    public static long byte2long(byte[] arr) {

        int result = 0;
        for (int i = 0; i < arr.length; i++) {
            result += (arr[i] & 0xff) << i * 8;
        }

        return result;
    }

    /**
     * @Author : 李道泉
     * @Description : long转byte
     * @Date 2018/4/2 16:14
     * @Modified by :
     */
    public static byte[] long2bytes(long num) {

        byte[] arr = new byte[8];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (byte) ((num >> i * 8) & 0xff);
        }

        return arr;
    }
}
